package zc.web;

import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/session")
public class SessionController {

	public static boolean isEmpty(String value) {
		return value == null || value.length() == 0;
	}
	
	/**
	 * @param session
	 * @return null if authenticated, "redirect:xxx" otherwise.
	 */
	private String checkAuth(HttpSession session) {
		if (session.getAttribute("userid") != null) {
			return null;
		} else {
			return "redirect:login";
		}
	}
	
	@RequestMapping(value="/home", method=RequestMethod.GET)
	public String home(HttpSession session) {
		String result = checkAuth(session);
		if (result != null) return result;
		
		return "home";
	}


	@RequestMapping(value="/logout", method=RequestMethod.POST)
	public String logout(HttpSession session) {
		session.invalidate();
		return "redirect:login";
	}

	
	public static class LoginForm {
		String username;
		String password;
		public String getUsername() {
			return username;
		}
		public void setUsername(String username) {
			this.username = username;
		}
		public String getPassword() {
			return password;
		}
		public void setPassword(String password) {
			this.password = password;
		}
	}
	
	@RequestMapping(value="/login", method=RequestMethod.POST)
	public String login(LoginForm loginForm, Model model, HttpSession session) {
		if (!isEmpty(loginForm.getUsername()) && 
				loginForm.getUsername().equals(loginForm.getPassword())) {
			session.setAttribute("userid", loginForm.getUsername());
			return "redirect:home";			
		} else {
			model.addAttribute("loginForm", loginForm);
			return "login";
		}
	}

	@RequestMapping(value="/login", method=RequestMethod.GET)
	public String login(HttpSession session) {
		String result = checkAuth(session);
		if (result == null) {
			return "redirect:home";
		} else {
			return "login";			
		}
	}
}
